from schedule import Schedule
import os
try:
    import cPickle as pickle
except:
    import pickle #in case they don't have cPickle

#============================================================
#    
class Archive(object):
    #============================================================
    #
    def __init__(self, manifestFile, archivePath, usePickle=True):
        self.usePickle    = usePickle
        self.manifest     = []
        self.archivePath  = archivePath
        self.manifestFile = manifestFile
        if isinstance(self.manifestFile, basestring):
            self.manifestFile = open(self.manifestFile)
        self.archiveSchedules = {}

    #============================================================
    #
    def loadArchive(cls, manifestFile, usePickle=True):
        archivePath = os.path.split(manifestFile)[0]
        archiveObj  = cls(manifestFile, archivePath, usePickle)
        if usePickle:
            archiveObj.manifest = pickle.load(archiveObj.manifestFile)
        else:
            archiveObj.manifest = cls.readTextManifestFile
        return archiveObj
    loadArchive = classmethod(loadArchive)
    
    #============================================================
    #
    def newArchive(cls, manifestFile, usePickle=True):
        archivePath         = os.path.split(manifestFile)[0]
        archiveObj          = cls(manifestFile, archivePath, usePickle)
        archiveObj.manifest = findXmlInArchive(archivePath)
        if usePickle:
            archiveObj.manifest = pickle.dump(archiveObj.manifest, archiveObj.manifestFile)
        else:
            for aFile in archiveObj.manifest:
                print >> manifestFile, aFile
        return archiveObj
    newArchive = classmethod(newArchive)

    #============================================================
    #
    def findXmlInArchive(archivePath):
        newManifest = []
        archiveDirFiles = os.listdir(archivePath)
        for aFile in archiveDirFiles:
            if aFile[-3:] == 'xml':
                newManifest.append(aFile)
        return newManifest
    findXmlInArchive = staticmethod(findXmlInArchive)
        
    #============================================================
    #
    def readTextManifestFile(manifestFile):
        return manifestFile.split(os.linesep)
    readTextManifestFile = staticmethod(readTextManifestFile)

    #============================================================
    #
    def getScheduleForArchiveFile(self, archiveFile):
        if manifestFile in self.archiveSchedules.keys():
            return self.archiveSchedules[archiveFile]
        scheduleObj = Schedule.makeScheduleFromXML(os.path.join(self.archivePath, archiveFile))
        self.archiveSchedules[archiveFile] = scheduleObj
        return scheduleObj
    
